using System;
using System.Collections.Generic;
using System.Linq;

namespace MT5Trade.Models
{
    // 类型别名，为了兼容性
    using Gap = GapHedgeData;

    /// <summary>
    /// 缺口对冲策略
    /// 识别价格缺口并计算最优对冲比例
    /// </summary>
    public class GapHedgingStrategy
    {
        #region 缺口类型定义

        /// <summary>
        /// 缺口方向
        /// </summary>
        public enum GapDirection
        {
            Up,      // 向上跳空
            Down,    // 向下跳空
            None     // 无缺口
        }

        #endregion

        #region 常量定义

        // 缺口识别参数
        public const double MIN_GAP_PERCENTAGE = 0.002;     // 最小缺口百分比（0.2%）
        public const double SIGNIFICANT_GAP_PERCENTAGE = 0.01;  // 显著缺口百分比（1%）
        public const double EXTREME_GAP_PERCENTAGE = 0.03;  // 极端缺口百分比（3%）
        
        // 成交量参数
        public const double HIGH_VOLUME_MULTIPLIER = 1.5;   // 高成交量倍数
        public const double LOW_VOLUME_MULTIPLIER = 0.7;    // 低成交量倍数
        
        // 对冲参数
        public const double DEFAULT_HEDGE_RATIO = 1.0;      // 默认对冲比例
        public const double MIN_HEDGE_RATIO = 0.3;          // 最小对冲比例
        public const double MAX_HEDGE_RATIO = 2.0;          // 最大对冲比例

        #endregion

        #region 私有字段

        private readonly List<GapHedgeData> _historicalGaps;
        private readonly Dictionary<string, double> _instrumentCorrelations;
        private GapHedgeData _lastIdentifiedGap;
        private DateTime _lastAnalysisTime;

        #endregion

        #region 构造函数

        /// <summary>
        /// 初始化缺口对冲策略
        /// </summary>
        public GapHedgingStrategy()
        {
            _historicalGaps = new List<GapHedgeData>();
            _instrumentCorrelations = new Dictionary<string, double>();
            _lastAnalysisTime = DateTime.MinValue;
        }

        #endregion

        #region 公共方法

        /// <summary>
        /// 计算趋势调整后的对冲比例
        /// </summary>
        /// <param name="baseHedgeRatio">基础对冲比例</param>
        /// <param name="trendStrength">趋势强度（-1到1）</param>
        /// <param name="gapDirection">缺口方向</param>
        /// <returns>调整后的对冲比例</returns>
        public double CalculateTrendAdjustedHedge(double baseHedgeRatio, double trendStrength, GapDirection gapDirection)
        {
            // 根据趋势强度调整对冲比例
            double adjustment = 1.0;

            if (gapDirection == GapDirection.Up)
            {
                // 上涨缺口：趋势越强，对冲比例越低（减少对冲）
                adjustment = 1.0 - trendStrength * 0.3;
            }
            else if (gapDirection == GapDirection.Down)
            {
                // 下跌缺口：趋势越强，对冲比例越高（增加对冲）
                adjustment = 1.0 + Math.Abs(trendStrength) * 0.3;
            }

            double adjustedRatio = baseHedgeRatio * adjustment;

            // 限制在合理范围内
            return Math.Max(MIN_HEDGE_RATIO, Math.Min(MAX_HEDGE_RATIO, adjustedRatio));
        }

        /// <summary>
        /// 计算流动性调整后的对冲规模
        /// </summary>
        /// <param name="baseHedgeSize">基础对冲规模</param>
        /// <param name="liquidityRatio">流动性比率</param>
        /// <returns>调整后的对冲规模</returns>
        public double CalculateLiquidityAdjustedHedge(double baseHedgeSize, double liquidityRatio)
        {
            // 流动性越低，对冲规模应该越小，以避免滑点
            if (liquidityRatio <= 0)
            {
                return 0;
            }

            double liquidityMultiplier = Math.Min(1.0, Math.Pow(liquidityRatio, 0.5));
            return baseHedgeSize * liquidityMultiplier;
        }

        /// <summary>
        /// 计算市场自适应对冲参数
        /// </summary>
        /// <param name="gapData">缺口数据</param>
        /// <param name="marketVolatility">市场波动率</param>
        /// <param name="correlationMatrix">相关性矩阵</param>
        /// <returns>市场自适应对冲结果</returns>
        public GapHedgeResult CalculateMarketAdaptiveHedgeResult(
            GapHedgeData gapData,
            double marketVolatility,
            Dictionary<string, double> correlationMatrix)
        {
            // 基础对冲比例
            double baseHedgeRatio = DEFAULT_HEDGE_RATIO;

            // 根据缺口类型调整
            switch (gapData.Type)
            {
                case GapType.Breakaway:
                    baseHedgeRatio = 1.2;  // 突破缺口需要更多对冲
                    break;
                case GapType.Continuation:
                    baseHedgeRatio = 1.0;  // 持续缺口标准对冲
                    break;
                case GapType.Exhaustion:
                    baseHedgeRatio = 1.5;  // 竭尽缺口高风险，需要更多对冲
                    break;
                case GapType.Common:
                    baseHedgeRatio = 0.5;  // 普通缺口较小对冲
                    break;
            }

            // 根据市场波动率调整
            double volatilityAdjustment = 1.0 + (marketVolatility - 0.15) * 2;
            volatilityAdjustment = Math.Max(0.5, Math.Min(2.0, volatilityAdjustment));

            double adjustedHedgeRatio = baseHedgeRatio * volatilityAdjustment;

            // 根据相关性调整
            double avgCorrelation = correlationMatrix.Values.Count > 0
                ? correlationMatrix.Values.Average()
                : 0.5;

            double correlationMultiplier = 1.0 + (1.0 - avgCorrelation) * 0.3;
            adjustedHedgeRatio *= correlationMultiplier;

            // 限制在合理范围内
            adjustedHedgeRatio = Math.Max(MIN_HEDGE_RATIO, Math.Min(MAX_HEDGE_RATIO, adjustedHedgeRatio));

            return new GapHedgeResult
            {
                GapData = gapData,
                HedgeRatio = adjustedHedgeRatio,
                PositionSize = gapData.GapSize * adjustedHedgeRatio,
                HedgeSize = gapData.GapSize * adjustedHedgeRatio,
                EffectiveDelta = adjustedHedgeRatio,
                HedgeEffectiveness = CalculateHedgeEffectiveness(adjustedHedgeRatio, avgCorrelation),
                Correlation = avgCorrelation,
                CostBenefit = CalculateCostBenefit(adjustedHedgeRatio, marketVolatility)
            };
        }

        private double CalculateHedgeEffectiveness(double hedgeRatio, double correlation)
        {
            // 对冲有效性 = 相关性 * 对冲比例的有效性
            double ratioEffectiveness = 1.0 - Math.Abs(hedgeRatio - 1.0) * 0.2;
            return correlation * ratioEffectiveness;
        }

        private double CalculateCostBenefit(double hedgeRatio, double volatility)
        {
            // 成本效益分析
            double hedgeCost = hedgeRatio * 0.001; // 假设每单位对冲成本为0.1%
            double riskReduction = hedgeRatio * volatility * 0.5;
            return riskReduction - hedgeCost;
        }

        #endregion

        #region 缺口识别

        /// <summary>
        /// 识别价格缺口
        /// </summary>
        /// <param name="prevClose">前收盘价</param>
        /// <param name="currentOpen">当前开盘价</param>
        /// <param name="currentHigh">当前最高价</param>
        /// <param name="currentLow">当前最低价</param>
        /// <param name="prevVolume">前一期成交量</param>
        /// <param name="currentVolume">当前成交量</param>
        /// <returns>缺口数据</returns>
        public GapHedgeData IdentifyGap(
            double prevClose, 
            double currentOpen,
            double currentHigh,
            double currentLow,
            double prevVolume,
            double currentVolume)
        {
            var gapData = new GapHedgeData
            {
                Timestamp = DateTime.UtcNow,
                PreviousClose = prevClose,
                CurrentOpen = currentOpen,
                CurrentHigh = currentHigh,
                CurrentLow = currentLow,
                PreviousVolume = prevVolume,
                CurrentVolume = currentVolume
            };

            // 计算缺口大小
            double gapSize = currentOpen - prevClose;
            double gapPercentage = Math.Abs(gapSize) / prevClose;
            
            gapData.GapSize = gapSize;
            gapData.GapPercentage = gapPercentage;

            // 判断缺口方向
            if (gapSize > 0 && gapPercentage >= MIN_GAP_PERCENTAGE)
            {
                gapData.Direction = GapDirection.Up;
                gapData.Type = ClassifyUpGap(gapPercentage, currentVolume / prevVolume);
            }
            else if (gapSize < 0 && gapPercentage >= MIN_GAP_PERCENTAGE)
            {
                gapData.Direction = GapDirection.Down;
                gapData.Type = ClassifyDownGap(gapPercentage, currentVolume / prevVolume);
            }
            else
            {
                gapData.Direction = GapDirection.None;
                gapData.Type = GapType.None;
            }

            // 计算缺口强度
            gapData.Strength = CalculateGapStrength(gapData);
            
            // 预测缺口回补概率
            gapData.FillProbability = EstimateGapFillProbability(gapData);

            // 记录历史
            if (gapData.Type != GapType.None)
            {
                _historicalGaps.Add(gapData);
                _lastIdentifiedGap = gapData;
                _lastAnalysisTime = DateTime.UtcNow;
            }

            return gapData;
        }

        /// <summary>
        /// 分类向上跳空缺口
        /// </summary>
        private GapType ClassifyUpGap(double gapPercentage, double volumeRatio)
        {
            if (gapPercentage >= EXTREME_GAP_PERCENTAGE)
            {
                // 极端缺口，可能是突破或竭尽
                if (volumeRatio >= HIGH_VOLUME_MULTIPLIER)
                {
                    return GapType.Breakaway;  // 高成交量支持，突破缺口
                }
                else
                {
                    return GapType.Exhaustion; // 成交量不足，竭尽缺口
                }
            }
            else if (gapPercentage >= SIGNIFICANT_GAP_PERCENTAGE)
            {
                // 显著缺口
                if (volumeRatio >= 1.0)
                {
                    return GapType.Continuation; // 持续缺口
                }
                else
                {
                    return GapType.Common; // 普通缺口
                }
            }
            else
            {
                return GapType.Common; // 小缺口归类为普通
            }
        }

        /// <summary>
        /// 分类向下跳空缺口
        /// </summary>
        private GapType ClassifyDownGap(double gapPercentage, double volumeRatio)
        {
            // 向下跳空的分类逻辑类似，但更关注恐慌性抛售
            if (gapPercentage >= EXTREME_GAP_PERCENTAGE)
            {
                if (volumeRatio >= HIGH_VOLUME_MULTIPLIER * 1.2) // 下跌需要更高成交量确认
                {
                    return GapType.Breakaway;
                }
                else
                {
                    return GapType.Exhaustion;
                }
            }
            else if (gapPercentage >= SIGNIFICANT_GAP_PERCENTAGE)
            {
                if (volumeRatio >= 1.2) // 下跌的持续缺口需要更高成交量
                {
                    return GapType.Continuation;
                }
                else
                {
                    return GapType.Common;
                }
            }
            else
            {
                return GapType.Common;
            }
        }

        /// <summary>
        /// 计算缺口强度
        /// </summary>
        private double CalculateGapStrength(GapHedgeData gap)
        {
            double strength = 0;

            // 基于缺口大小
            strength += gap.GapPercentage * 100;

            // 基于成交量
            double volumeRatio = gap.CurrentVolume / Math.Max(1, gap.PreviousVolume);
            strength += Math.Min(volumeRatio * 10, 30);

            // 基于缺口类型
            switch (gap.Type)
            {
                case GapType.Breakaway:
                    strength *= 1.5;
                    break;
                case GapType.Continuation:
                    strength *= 1.2;
                    break;
                case GapType.Exhaustion:
                    strength *= 0.8;
                    break;
                case GapType.Common:
                    strength *= 0.6;
                    break;
            }

            return Math.Min(100, strength); // 限制在0-100范围
        }

        /// <summary>
        /// 估计缺口回补概率
        /// </summary>
        private double EstimateGapFillProbability(GapHedgeData gap)
        {
            double probability = 0.5; // 基础概率50%

            // 根据缺口类型调整
            switch (gap.Type)
            {
                case GapType.Common:
                    probability = 0.8; // 普通缺口80%概率回补
                    break;
                case GapType.Exhaustion:
                    probability = 0.7; // 竭尽缺口70%概率回补
                    break;
                case GapType.Continuation:
                    probability = 0.4; // 持续缺口40%概率回补
                    break;
                case GapType.Breakaway:
                    probability = 0.2; // 突破缺口20%概率回补
                    break;
            }

            // 根据成交量调整
            double volumeRatio = gap.CurrentVolume / Math.Max(1, gap.PreviousVolume);
            if (volumeRatio < LOW_VOLUME_MULTIPLIER)
            {
                probability += 0.1; // 低成交量增加回补概率
            }
            else if (volumeRatio > HIGH_VOLUME_MULTIPLIER)
            {
                probability -= 0.1; // 高成交量降低回补概率
            }

            return Math.Max(0, Math.Min(1, probability));
        }

        #endregion

        #region Delta中性对冲计算

        /// <summary>
        /// 计算Delta中性对冲比例
        /// </summary>
        /// <param name="gap">缺口数据</param>
        /// <param name="positionSize">主仓位大小</param>
        /// <param name="positionDelta">主仓位Delta值</param>
        /// <param name="hedgeInstrumentDelta">对冲工具Delta值</param>
        /// <param name="correlation">相关系数</param>
        /// <returns>对冲策略结果</returns>
        public GapHedgeResult CalculateDeltaNeutralHedge(
            GapHedgeData gap,
            double positionSize,
            double positionDelta,
            double hedgeInstrumentDelta,
            double correlation = 1.0)
        {
            var result = new GapHedgeResult
            {
                GapData = gap,
                PositionSize = positionSize,
                PositionDelta = positionDelta,
                Correlation = correlation
            };

            // 计算需要对冲的Delta
            double totalDelta = positionSize * positionDelta;
            
            // 考虑缺口影响调整Delta
            double gapAdjustment = 1.0;
            switch (gap.Type)
            {
                case GapType.Breakaway:
                    gapAdjustment = 1.3; // 突破缺口增加对冲
                    break;
                case GapType.Continuation:
                    gapAdjustment = 1.1; // 持续缺口适度增加
                    break;
                case GapType.Exhaustion:
                    gapAdjustment = 0.9; // 竭尽缺口减少对冲
                    break;
                case GapType.Common:
                    gapAdjustment = 0.8; // 普通缺口减少对冲
                    break;
            }
            
            double adjustedDelta = totalDelta * gapAdjustment;
            
            // 计算对冲数量（考虑相关性）
            double hedgeSize = -adjustedDelta / (hedgeInstrumentDelta * correlation);
            
            // 应用对冲比例限制
            double hedgeRatio = Math.Abs(hedgeSize / positionSize);
            hedgeRatio = Math.Max(MIN_HEDGE_RATIO, Math.Min(MAX_HEDGE_RATIO, hedgeRatio));
            
            // 重新计算对冲数量
            hedgeSize = positionSize * hedgeRatio * Math.Sign(hedgeSize);
            
            result.HedgeSize = hedgeSize;
            result.HedgeRatio = hedgeRatio;
            result.EffectiveDelta = totalDelta + (hedgeSize * hedgeInstrumentDelta * correlation);
            result.HedgeEffectiveness = 1.0 - Math.Abs(result.EffectiveDelta / totalDelta);
            
            // 生成建议
            result.Recommendation = GenerateHedgeRecommendation(gap, result);
            
            return result;
        }

        /// <summary>
        /// 生成对冲建议
        /// </summary>
        private string GenerateHedgeRecommendation(GapHedgeData gap, GapHedgeResult result)
        {
            string recommendation = $"缺口类型: {gap.Type}, 方向: {gap.Direction}, 强度: {gap.Strength:F1}\n";
            
            if (gap.Type == GapType.Breakaway)
            {
                recommendation += "突破缺口建议: 增加对冲比例，预期趋势延续\n";
            }
            else if (gap.Type == GapType.Exhaustion)
            {
                recommendation += "竭尽缺口建议: 准备反向操作，逐步减少对冲\n";
            }
            else if (gap.Type == GapType.Common)
            {
                recommendation += "普通缺口建议: 等待回补，维持基本对冲\n";
            }
            
            recommendation += $"建议对冲比例: {result.HedgeRatio:P1}, ";
            recommendation += $"对冲有效性: {result.HedgeEffectiveness:P1}";
            
            return recommendation;
        }

        #endregion

        #region 历史分析

        /// <summary>
        /// 获取历史缺口统计
        /// </summary>
        public GapHedgeStatistics GetHistoricalStatistics()
        {
            if (_historicalGaps.Count == 0)
            {
                return new GapHedgeStatistics();
            }

            var stats = new GapHedgeStatistics
            {
                TotalGaps = _historicalGaps.Count,
                UpGaps = _historicalGaps.Count(g => g.Direction == GapDirection.Up),
                DownGaps = _historicalGaps.Count(g => g.Direction == GapDirection.Down),
                AverageGapSize = _historicalGaps.Average(g => Math.Abs(g.GapPercentage)),
                
                BreakawayGaps = _historicalGaps.Count(g => g.Type == GapType.Breakaway),
                ContinuationGaps = _historicalGaps.Count(g => g.Type == GapType.Continuation),
                ExhaustionGaps = _historicalGaps.Count(g => g.Type == GapType.Exhaustion),
                CommonGaps = _historicalGaps.Count(g => g.Type == GapType.Common)
            };
            
            // 计算成功率（如果有跟踪数据）
            var filledGaps = _historicalGaps.Where(g => g.IsFilled).ToList();
            if (filledGaps.Any())
            {
                stats.GapFillRate = (double)filledGaps.Count / _historicalGaps.Count;
                stats.AverageFillTime = TimeSpan.FromHours(
                    filledGaps.Average(g => (g.FillTime ?? g.Timestamp).Subtract(g.Timestamp).TotalHours));
            }
            
            return stats;
        }

        /// <summary>
        /// 更新缺口回补状态
        /// </summary>
        public void UpdateGapFillStatus(double currentPrice)
        {
            foreach (var gap in _historicalGaps.Where(g => !g.IsFilled))
            {
                bool isFilled = false;

                if (gap.Direction == GapDirection.Up)
                {
                    // 向上缺口，价格回落到缺口下沿
                    isFilled = currentPrice <= gap.PreviousClose;
                }
                else if (gap.Direction == GapDirection.Down)
                {
                    // 向下缺口，价格回升到缺口上沿
                    isFilled = currentPrice >= gap.PreviousClose;
                }

                if (isFilled)
                {
                    gap.IsFilled = true;
                    gap.FillTime = DateTime.UtcNow;
                }
            }
        }

        #endregion

        #region 市场自适应对冲方法

        /// <summary>
        /// 根据市场条件计算自适应对冲策略
        /// </summary>
        /// <param name="gap">缺口数据</param>
        /// <param name="marketVolatility">市场波动率</param>
        /// <param name="correlationMatrix">相关性矩阵</param>
        /// <returns>市场自适应对冲参数</returns>
        public MarketAdaptiveHedgeParams CalculateMarketAdaptiveHedge(
            GapHedgeData gap,
            double marketVolatility,
            Dictionary<string, double> correlationMatrix)
        {
            var result = new MarketAdaptiveHedgeParams();

            // 基础对冲比例
            double baseHedgeRatio = DEFAULT_HEDGE_RATIO;

            // 根据缺口类型调整
            switch (gap?.Type ?? GapType.None)
            {
                case GapType.Breakaway:
                    baseHedgeRatio *= 1.4;  // 突破缺口增加对冲
                    break;
                case GapType.Continuation:
                    baseHedgeRatio *= 1.2;  // 持续缺口适度增加
                    break;
                case GapType.Exhaustion:
                    baseHedgeRatio *= 0.9;  // 竭尽缺口减少对冲
                    break;
                case GapType.Common:
                    baseHedgeRatio *= 0.8;  // 普通缺口少量对冲
                    break;
            }

            // 根据市场波动率调整
            // 高波动率时增加对冲比例和频率
            double volatilityMultiplier = 1.0;
            if (marketVolatility > 0.15)  // 高波动（年化15%以上）
            {
                volatilityMultiplier = 1.5;
                result.RebalanceFrequency = 4;  // 每天4次
            }
            else if (marketVolatility > 0.08)  // 中等波动
            {
                volatilityMultiplier = 1.2;
                result.RebalanceFrequency = 2;  // 每天2次
            }
            else  // 低波动
            {
                volatilityMultiplier = 1.0;
                result.RebalanceFrequency = 1;  // 每天1次
            }

            // 计算相关性调整
            double avgCorrelation = correlationMatrix?.Any() == true
                ? correlationMatrix.Values.Average()
                : 1.0;
            double correlationAdjustment = Math.Sqrt(Math.Abs(avgCorrelation));

            // 计算最终对冲比例
            result.HedgeRatio = baseHedgeRatio * volatilityMultiplier * correlationAdjustment;
            result.HedgeRatio = Math.Max(MIN_HEDGE_RATIO, Math.Min(MAX_HEDGE_RATIO, result.HedgeRatio));

            // 设置其他参数
            result.PositionSizeAdjustment = marketVolatility > 0.3 ? 0.7 : 1.0;  // 高波动时减小仓位
            result.StopLossDistance = marketVolatility * 2;  // 止损距离为2倍波动率
            result.TakeProfitDistance = marketVolatility * 3;  // 止盈距离为3倍波动率
            result.MaxDrawdownLimit = 0.1;  // 最大回撤限制10%

            // 市场压力条件下的稳定性控制
            if (marketVolatility > 0.4)  // 极端波动
            {
                result.UseEmergencyProtocol = true;
                result.HedgeRatio = Math.Min(result.HedgeRatio, 1.5);  // 限制最大对冲比例
                result.PositionSizeAdjustment *= 0.5;  // 进一步减小仓位
            }

            return result;
        }

        /// <summary>
        /// 根据价格数据计算市场自适应对冲（重载方法）
        /// </summary>
        /// <param name="prices">历史价格数据</param>
        /// <returns>市场自适应对冲参数</returns>
        public MarketAdaptiveHedgeParams CalculateMarketAdaptiveHedge(double[] prices)
        {
            // 计算历史波动率
            double volatility = CalculateVolatility(prices);

            // 识别最近的缺口
            GapHedgeData latestGap = null;
            if (prices.Length >= 2)
            {
                latestGap = IdentifyGap(
                    prices[prices.Length - 2],  // prevClose
                    prices[prices.Length - 1],  // currentOpen
                    prices.Max(),               // high
                    prices.Min(),               // low
                    1000,                        // prevVolume (默认值)
                    1000);                       // currentVolume (默认值)
            }

            // 使用默认相关性矩阵
            var correlationMatrix = new Dictionary<string, double> { { "Default", 0.8 } };

            return CalculateMarketAdaptiveHedge(latestGap, volatility, correlationMatrix);
        }

        /// <summary>
        /// 计算价格序列的波动率
        /// </summary>
        private double CalculateVolatility(double[] prices)
        {
            if (prices == null || prices.Length < 2)
                return 0.2;  // 默认波动率20%

            var returns = new double[prices.Length - 1];
            for (int i = 1; i < prices.Length; i++)
            {
                returns[i - 1] = Math.Log(prices[i] / prices[i - 1]);
            }

            double mean = returns.Average();
            double variance = returns.Select(r => Math.Pow(r - mean, 2)).Average();
            return Math.Sqrt(variance * 252);  // 年化波动率
        }

        #endregion
    }

    #region 数据结构定义

    /// <summary>
    /// 缺口对冲数据
    /// </summary>
    public class GapHedgeData
    {
        public DateTime Timestamp { get; set; }
        public GapType Type { get; set; }
        public GapHedgingStrategy.GapDirection Direction { get; set; }
        public double PreviousClose { get; set; }
        public double CurrentOpen { get; set; }
        public double CurrentHigh { get; set; }
        public double CurrentLow { get; set; }
        public double GapSize { get; set; }
        public double GapPercentage { get; set; }
        public double PreviousVolume { get; set; }
        public double CurrentVolume { get; set; }
        public double Strength { get; set; }
        public double FillProbability { get; set; }
        public bool IsFilled { get; set; }
        public DateTime? FillTime { get; set; }

        // 兼容性属性
        public double Size => GapSize;
        public double Percentage => GapPercentage;
        public bool IsUpward => Direction == GapHedgingStrategy.GapDirection.Up;
        public double VolumeRatio => CurrentVolume > 0 && PreviousVolume > 0 ? CurrentVolume / PreviousVolume : 1.0;
        public double Confidence { get; set; }
        
        public override string ToString()
        {
            return $"{Type} Gap: {GapPercentage:P2}, Direction: {Direction}, Strength: {Strength:F1}";
        }
    }

    /// <summary>
    /// 对冲结果
    /// </summary>
    public class GapHedgeResult
    {
        public GapHedgeData GapData { get; set; }
        public double PositionSize { get; set; }
        public double PositionDelta { get; set; }
        public double HedgeSize { get; set; }
        public double HedgeRatio { get; set; }
        public double EffectiveDelta { get; set; }
        public double HedgeEffectiveness { get; set; }
        public double Correlation { get; set; }
        public string Recommendation { get; set; }
        public double CostBenefit { get; set; }
    }

    /// <summary>
    /// 缺口对冲统计
    /// </summary>
    public class GapHedgeStatistics
    {
        public int TotalGaps { get; set; }
        public int UpGaps { get; set; }
        public int DownGaps { get; set; }
        public double AverageGapSize { get; set; }
        public int BreakawayGaps { get; set; }
        public int ContinuationGaps { get; set; }
        public int ExhaustionGaps { get; set; }
        public int CommonGaps { get; set; }
        public double GapFillRate { get; set; }
        public TimeSpan AverageFillTime { get; set; }
    }

    /// <summary>
    /// 市场自适应对冲参数
    /// </summary>
    public class MarketAdaptiveHedgeParams
    {
        /// <summary>
        /// 对冲比例
        /// </summary>
        public double HedgeRatio { get; set; }

        /// <summary>
        /// 再平衡频率（每天次数）
        /// </summary>
        public int RebalanceFrequency { get; set; }

        /// <summary>
        /// 仓位大小调整系数
        /// </summary>
        public double PositionSizeAdjustment { get; set; }

        /// <summary>
        /// 止损距离（波动率的倍数）
        /// </summary>
        public double StopLossDistance { get; set; }

        /// <summary>
        /// 止盈距离（波动率的倍数）
        /// </summary>
        public double TakeProfitDistance { get; set; }

        /// <summary>
        /// 最大回撤限制
        /// </summary>
        public double MaxDrawdownLimit { get; set; }

        /// <summary>
        /// 是否启用紧急协议
        /// </summary>
        public bool UseEmergencyProtocol { get; set; }
    }

    #endregion
}